package com.haixiaoke.saas.lock.service.impl;

import java.time.*;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.DeviceLockConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.lock.domain.DeviceLock;
import com.haixiaoke.saas.lock.domain.LockFace;
import com.haixiaoke.saas.lock.domain.LockPwd;
import com.haixiaoke.saas.lock.mapper.LockPwdMapper;
import com.haixiaoke.saas.lock.service.IDeviceLockService;
import com.haixiaoke.saas.lock.service.ILockFaceService;
import com.haixiaoke.saas.lock.service.ILockPwdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 锁密码授权Service业务层处理
 *
 * @author panda
 * @date 2025-06-26
 */
@Service
public class LockPwdServiceImpl implements ILockPwdService {
    @Autowired
    private LockPwdMapper lockPwdMapper;
    @Autowired
    private IDeviceLockService deviceLockService;
    @Autowired
    private LockDevicesService lockDevicesService;
    @Autowired
    private ILockFaceService lockFaceService;

    /**
     * 查询锁密码授权
     *
     * @param pwdId 锁密码授权主键
     * @return 锁密码授权
     */
    @Override
    public LockPwd selectLockPwdByPwdId(Long pwdId) {
        return lockPwdMapper.selectLockPwdByPwdId(pwdId);
    }

    /**
     * 查询锁密码授权列表
     *
     * @param lockPwd 锁密码授权
     * @return 锁密码授权
     */
    @Override
    public List<LockPwd> selectLockPwdList(LockPwd lockPwd) {
        return lockPwdMapper.selectLockPwdList(lockPwd);
    }

    /**
     * 新增锁密码授权
     *
     * @param lockPwd 锁密码授权
     * @return 结果
     */
    @Override
    public AjaxResult insertLockPwd(LockPwd lockPwd) {
        if (lockPwd.getLockId() == null) {
            return AjaxResult.error("请选择锁");
        }
        String password = null;
        if (StrUtil.isNotBlank(lockPwd.getIdentification())) {
            //随机生成密码
            password = RandomUtil.randomNumbers(6);
            lockPwd.setPassword(password);
        }
        if (StrUtil.isBlank(lockPwd.getPassword()) || lockPwd.getPassword().length() < 6) {
            return AjaxResult.error("密码格式有误,请输入6位数字密码");
        }
        if (lockPwd.getConUserId() != null) {
            LockFace face = lockFaceService.selectLockFaceByLockIdAndUserId(lockPwd.getLockId(), lockPwd.getConUserId());
            if (ObjectUtil.isEmpty(face)) {
                return AjaxResult.error("承租用户未上传授权信息");
            }
            if (StrUtil.equals(DeviceLockConstants.LESSEE_FLAG_NO, face.getLesseeFlag())) {
                return AjaxResult.error("非承租人不能申请密码");
            }
            int pwdNum = lockPwdMapper.checkPwdNumByUser(lockPwd);
            if (pwdNum >= 3) {
                return AjaxResult.error("承租人每月最多申请3个密码");
            }
            lockPwd.setUserName(face.getUserName());
        }
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁数据异常");
        }
        Date nowDate = DateUtils.getNowDate();
        LocalDate nowLocalDate = LocalDate.now();
        ZonedDateTime zonedDateTime = lockPwd.getAuthStartTime().toInstant().atZone(ZoneId.systemDefault());
        if (nowLocalDate.isAfter(zonedDateTime.toLocalDate())) {
            return AjaxResult.error("授权开始时间不可小于当前时间");
        }
        lockPwd.setCreateTime(nowDate);
        lockPwd.setIdentification(lockDevicesService.getIdentification());

        int result = lockPwdMapper.insertLockPwd(lockPwd);
        if (result > 0) {
            lockDevicesService.createLockPwd(lockPwd.getAuthStartTime(), lockPwd.getAuthEndTime(),
                    lock.getLockMac(), lockPwd.getPassword(), lockPwd.getIdentification());
            return AjaxResult.success(password);
        }
        return AjaxResult.error();
    }

    /**
     * 修改锁密码授权
     *
     * @param lockPwd 锁密码授权
     * @return 结果
     */
    @Override
    public int updateLockPwd(LockPwd lockPwd) {
        lockPwd.setUpdateTime(DateUtils.getNowDate());
        return lockPwdMapper.updateLockPwd(lockPwd);
    }

    /**
     * 批量删除锁密码授权
     *
     * @param pwdIds 需要删除的锁密码授权主键
     * @return 结果
     */
    @Override
    public int deleteLockPwdByPwdIds(Long[] pwdIds) {
        return lockPwdMapper.deleteLockPwdByPwdIds(pwdIds);
    }

    /**
     * 删除锁密码授权信息
     *
     * @param pwdId 锁密码授权主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteLockPwdByPwdId(Long pwdId) {
        LockPwd lockPwd = lockPwdMapper.selectLockPwdByPwdId(pwdId);
        if (ObjectUtil.isEmpty(lockPwd)) {
            return AjaxResult.error("锁密码不存在");
        }
        DeviceLock deviceLock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(deviceLock)) {
            return AjaxResult.error("锁不存在");
        }
        if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_ENABLE, lockPwd.getPwdState())) {
            lockDevicesService.removeLockPwd(deviceLock.getLockMac(), lockPwd.getIdentification());
        }
        int result = lockPwdMapper.deleteLockPwdByPwdId(pwdId);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public int deleteLockPwdByLockId(Long lockId) {
        return lockPwdMapper.deleteLockPwdByLockId(lockId);
    }

    @Override
    public AjaxResult editPwdState(Long pwdId) {
        LockPwd lockPwd = lockPwdMapper.selectLockPwdByPwdId(pwdId);
        if (ObjectUtil.isEmpty(lockPwd)) {
            return AjaxResult.error("锁密码不存在");
        }
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁不存在");
        }

        Date nowDate = DateUtils.getNowDate();
        if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_ENABLE, lockPwd.getPwdState())) {
            lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_FORBIDDEN);
            lockDevicesService.removeLockPwd(lock.getLockMac(), lockPwd.getIdentification());
        } else if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_FORBIDDEN, lockPwd.getPwdState())) {
            lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_ENABLE);
            lockDevicesService.createLockPwd(nowDate, DateUtils.addYears(nowDate, 10), lock.getLockMac(),
                    lockPwd.getPassword(), lockPwd.getIdentification());
        }
        lockPwd.setUpdateTime(nowDate);
        int result = lockPwdMapper.updateLockPwd(lockPwd);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<LockPwd> selectLockListByIdentifications(List<String> identifications) {
        return lockPwdMapper.selectLockListByIdentifications(identifications);
    }
}
